﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.IO;


namespace lcmyjobs.BLL
{
    /// <summary>
    /// 电子邮件发送类
    /// </summary>
    public class SendEmail
    {
        SmtpClient SmtpClient = null;   //设置SMTP协议
        MailAddress MailAddress_from = null; //设置发信人地址  当然还需要密码
        MailAddress MailAddress_to = null;  //设置收信人地址  不需要密码
        MailMessage MailMessage_Mai = null;
        FileStream FileStream_my = null; //附件文件流
        lcmyjobs.Model.email email;


        public SendEmail(lcmyjobs.Model.email email)
        {
            this.email = email;
            //MailMessage_Mai = new MailMessage();
        }
        /// <summary>
        /// 设置Ｓmtp服务器信息
        /// </summary>
        /// <param name="ServerName">SMTP服务名</param>
        /// <param name="Port">端口号(-1表示默认值，smtp为110，pop为25)</param>
        private void setSmtpClient(string serverHost, int port)
        {
            SmtpClient = new SmtpClient();
            SmtpClient.Host = serverHost;//指定SMTP服务名  例如QQ邮箱为 smtp.qq.com 新浪cn邮箱为 smtp.sina.cn等

            //if (port == -1)
            //{
            //    SmtpClient.Port = 110;
            //}
            //else
            //{
            //    SmtpClient.Port = port;
            //}
            
            //SmtpClient.Port = port; //指定端口号
            SmtpClient.Timeout = 0;  //超时时间

        }

        /// <summary>
        /// 验证发件人信息
        /// </summary>
        /// <param name="MailAddress">发件邮箱地址</param>
        /// <param name="MailPwd">邮箱密码</param>
        private void setAddressform(string MailAddress, string MailPwd)
        {
            //创建服务器认证
            NetworkCredential NetworkCredential_my = new NetworkCredential(MailAddress, MailPwd);
            //实例化发件人地址
            MailAddress_from = new System.Net.Mail.MailAddress(MailAddress,null);
            //指定发件人信息  包括邮箱地址和邮箱密码
            SmtpClient.Credentials = new System.Net.NetworkCredential(MailAddress_from.Address, MailPwd);
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="receives"></param>
        public void Send()
        {
            string msg1 = "";
            string msg2 = "";
            try
            {
                setSmtpClient(email.serverhost, email.port);
                msg1 = "设置smtp服务器成功！";
            }
            catch (Exception ex)
            {
                msg1 = "邮件发送失败,请确定SMTP服务名是否正确！" + "\n" + "技术信息:\n" + ex.Message;
                
            }
            try
            {
                setAddressform(email.sendEmailAdd, email.sendEmailPwd);
                
            }
            catch (Exception ex)
            {
                msg2 = "邮件发送失败,请确定发件邮箱地址和密码的正确性！" + "\n" + "技术信息:\n" + ex.Message;
               
            }
            //清空历史发送信息 以防发送时收件人收到的错误信息(收件人列表会不断重复)
            MailMessage_Mai = new MailMessage();
            MailMessage_Mai.To.Clear();

            string[] receives = email.receiveEmailAdd.Split(',');

            if (receives.Length > 0)
            {
                //添加收件人邮箱地址
                foreach (string receive in receives)
                {
                    MailAddress_to = new MailAddress(receive);
                    MailMessage_Mai.To.Add(MailAddress_to);
                }

                //发件人邮箱
                MailMessage_Mai.From = MailAddress_from;
                //邮件主题
                MailMessage_Mai.Subject = email.title;
                MailMessage_Mai.SubjectEncoding = System.Text.Encoding.UTF8;
                //邮件正文
                MailMessage_Mai.Body = email.content;
                MailMessage_Mai.BodyEncoding = System.Text.Encoding.UTF8;

                // liuhui add for forget password mail
                MailMessage_Mai.IsBodyHtml = true;
                //清空历史附件  以防附件重复发送
                //MailMessage_Mai.Attachments.Clear();
                //添加附件
                //MailMessage_Mai.Attachments.Add(new Attachment(txt_Path.Text.Trim(), MediaTypeNames.Application.Octet));
                //开始发送邮件
                //SmtpClient.SendAsync(MailMessage_Mai, "000000000");
                SmtpClient.Send(MailMessage_Mai);

                //注册邮件发送完毕后的处理事件
                //SmtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); 
            }
          
           

        }

        //private static void sendcompletedcallback(object sender, asynccompletedeventargs e)
        //{
        //    try
        //    {
        //        if (e.cancelled)
        //        {
        //            messagebox.show("发送已取消！");
        //        }
        //        if (e.error != null)
        //        {

        //            messagebox.show("邮件发送失败！" + "\n" + "技术信息:\n" + e.tostring(), "错误", messageboxbuttons.ok, messageboxicon.error);

        //        }
        //        else
        //        {
        //            messagebox.show("邮件成功发出!", "恭喜!", messageboxbuttons.ok, messageboxicon.information);
        //        }
        //    }
        //    catch (exception ex)
        //    {
        //        messagebox.show("邮件发送失败！" + "\n" + "技术信息:\n" + ex.message, "错误", messageboxbuttons.ok, messageboxicon.error);
        //    }

        //}

        #region 检查附件大小
        private bool Attachment_MaiInit(string path,out string msg)
        {

            try
            {
                FileStream_my = new FileStream(path, FileMode.Open);
                string name = FileStream_my.Name;
                int size = (int)(FileStream_my.Length / 1024 / 1024);
                FileStream_my.Close();
                //控制文件大小不大于10Ｍ
                if (size > 10)
                {
                    msg = "文件长度不能大于10M！你选择的文件大小为"+ size.ToString()+"M";
                    return false;
                }
                else
                {
                    msg = "添加附件成功！";
                    return true;
                }

                
            }
            catch (IOException ex)
            {
                msg = "出错了！"+ex.ToString();
                return false;
            }

        }
        #endregion
    }
}
